package com.budwk.app.jim.client;

import org.jim.client.ImClientChannelContext;
import org.jim.client.JimClient;
import org.jim.client.JimClientAPI;
import org.jim.client.config.ImClientConfig;
import org.jim.core.packets.ChatBody;
import org.jim.core.packets.ChatType;
import org.jim.core.packets.Command;
import org.jim.core.tcp.TcpPacket;
import org.tio.client.ReconnConf;
import org.tio.core.Node;

/**
 * @author ZY.Wang
 * @since 2023/6/15
 */
public class JimSender {

    public static ImClientChannelContext imClientChannelContext = null;

    public static void initChannel() {
        try {
            Node serverNode = new Node("localhost", 18090);
            //构建客户端配置信息
            ImClientConfig imClientConfig = ImClientConfig.newBuilder()
                    //客户端业务回调器,不可以为NULL
                    .clientHandler(new JimImClientHandler())
                    //客户端事件监听器，可以为null，但建议自己实现该接口
                    .clientListener(new JimImClientListener())
                    //心跳时长不设置，就不发送心跳包
                    // .heartbeatTimeout(5000)
                    //断链后自动连接的，不想自动连接请设为null
                    .reConnConf(new ReconnConf(200L))
                    .build();
            //生成客户端对象;
            JimClient jimClient = new JimClient(imClientConfig);
            //连接服务端
            imClientChannelContext = jimClient.connect(serverNode);
            if (imClientChannelContext != null) System.out.println("jim客户端初始化成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void sendText(String msg, String userId, String toUserId) {
        if (imClientChannelContext == null) initChannel();
        ChatBody chatBody = ChatBody.newBuilder()
                .from(userId)
                .to(toUserId)
                .msgType(0)
                .chatType(ChatType.CHAT_TYPE_PRIVATE.getNumber())
                .groupId("")
                .content(msg)
                .addExtra("","").build();
        TcpPacket chatPacket = new TcpPacket(Command.COMMAND_CHAT_REQ, chatBody.toByte());
        boolean send = JimClientAPI.send(imClientChannelContext, chatPacket);
        System.out.println(send);
    }
}
